package com.mdw.jsontest.json;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.stream.Collectors;


/**
 * @author Sai
 * Created by Sai on 2019-03-15.
 */
@WebServlet(urlPatterns = {"/json"})
public class JsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /**
         *
         */
    }

    // 获取前端post提交的json字符串，并转换为对象；再把对象转为json字符串，生成响应返回前端。
    // curl -v -H "Content-Type: application/json" http://localhost:8080/webapp-demo/json -X POST --data '{"姓名":"莫冬旺","年龄":"21"}'
    // 注意改成自己的网址啊！！！
    // curl -v -H "Content-Type: application/json" http://localhost:8080/StudentJson_war/json -X POST --data '{"姓名":"莫冬旺","年龄":"21"}'
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Jsonb jsonb = JsonbBuilder.create();
        String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        // 利用jsonb把json字符串转换为对象
        PersonDTO personDTO = jsonb.fromJson(postJsonString, PersonDTO.class);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        String jsonPerson = "code\":0,\"msg\":\"操作成功";
        resp.getWriter().println(jsonPerson);
    }
}
